#include <iostream>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <cstring>
#include <memory>
#include <unistd.h>
#include <fcntl.h>
#include <cerrno> // 用于 errno
#include <string>

void Run(int port)
{
    struct sockaddr_in host;
    host.sin_family = AF_INET;
    host.sin_port = htons(port);
    host.sin_addr.s_addr = INADDR_ANY;

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        std::cerr << "创建套接字失败: " << strerror(errno) << std::endl;
        exit(1);
    }

    if (bind(sockfd, (struct sockaddr*)&host, sizeof(host)) < 0) {
        std::cerr << "绑定地址失败: " << strerror(errno) << std::endl;
        exit(1);
    }

    if (listen(sockfd, 10) < 0) {
        std::cerr << "监听失败: " << strerror(errno) << std::endl;
        exit(1);
    }

    while (true)
    {
        struct sockaddr_in client;
        socklen_t len = sizeof(client);
        int connfd = accept(sockfd, (struct sockaddr*)&client, &len);
        if (connfd < 0) {
            std::cerr << "接受连接失败, 错误码: " << errno << " (" << strerror(errno) << ")" << std::endl;
            continue;
        }

        std::cout << "客户端连接: " << inet_ntoa(client.sin_addr) << ":" << ntohs(client.sin_port) << std::endl;
        char buffer[1024];
        memset(buffer, 0, sizeof(buffer));

        while (true)
        {
            int n = read(connfd, buffer, sizeof(buffer));
            if (n <= 0) {
                break;
            }

            std::cout << "收到数据: " << buffer << std::endl;
            std::string echo = "echo: " + std::string(buffer);
            ssize_t bytes_sent = write(connfd, echo.c_str(), echo.size());
            if (bytes_sent < 0) {
                std::cerr << "发送数据失败: " << strerror(errno) << std::endl;
                break;
            }
        }

        close(connfd); // 关闭连接
    }

    close(sockfd); // 关闭监听套接字
}

int main(int argc, char* argv[])
{
    if (argc != 2) {
        std::cerr << "参数错误" << std::endl;
        std::cout << "Usage: " << argv[0] << " port" << std::endl;
        return -1;
    }

    int port = atoi(argv[1]);
    Run(port);

    return 0;
}
